package com.wanmait.gohome.controller.manage;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@WebServlet("/Code")
public class Code extends HttpServlet {
    private Random random = new Random();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();

        //绘图，在内存中
        int w = 160;
        int h = 60;
        BufferedImage bi = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, w, h);


        for(int i=0;i<20;i++) {
            g.setColor(this.getRandomColor());
            g.drawLine(random.nextInt(w),random.nextInt(h), random.nextInt(w),random.nextInt(h));
        }


        String randCode = this.getRandomString(4);
        request.getSession().setAttribute("randcode", randCode);

        for(int i=0;i<randCode.length();i++) {
            int x,y;
            x = i*28+random.nextInt(25);
            y = h-30+random.nextInt(30);
            String ch = randCode.charAt(i)+"";
            g.setColor(this.getRandomColor());

            g.setFont(new Font("黑体", Font.BOLD,25+random.nextInt(10)));
            g.drawString(ch, x, y);
        }

        g.setColor(Color.WHITE);
        for(int i=0;i<20;i++) {
            g.drawLine(random.nextInt(w),random.nextInt(h), random.nextInt(w),random.nextInt(h));
        }

        ImageIO.write(bi, "jpeg", out);
    }
    private Color getRandomColor() {
        int r = random.nextInt(200);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r,g,b);
    }
    private String getRandomString(int len) {
        String str = "";
        for(int i=0;i<len;i++) {
            str += (char)('A'+random.nextInt(26));
            //str += MES.charAt(random.nextInt(MES.length()));
        }
        return str;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
